package com.hyfrogx.modules.manage.controller.course;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.param.JSONResult;
import com.hyfrogx.common.param.LiResult;
import com.hyfrogx.common.qcloud.UploadUtils;
import com.hyfrogx.common.utils.Constant;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.manage.controller.BaseController;
import com.hyfrogx.modules.manage.entity.GoodsTest;
import com.hyfrogx.modules.manage.entity.course.CourseManageEntity;
import com.hyfrogx.modules.manage.entity.course.CourseManageSectionEntity;
import com.hyfrogx.modules.manage.form.InfoForm;
import com.hyfrogx.modules.manage.form.course.AddCourseManageForm;
import com.hyfrogx.modules.manage.service.course.CourseManageSectionService;
import com.hyfrogx.modules.manage.service.course.CourseManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
/**
 * @author 罗春杰-技术部
 */
@RestController
@Api(value = "CourseManageController",tags = {"后台-课程管理控制类"})
@RequestMapping("courseManage")
public class CourseManageController  extends BaseController {

    @Autowired
    private CourseManageService manageService;

    @Autowired
    private UserService userService;

    @Autowired
    private CourseManageSectionService sectionService;

    /**
     * 富文本编辑器整段内容上传
     * @param
     * @return
            */
    @ApiOperation("富文本编辑器整段内容上传")
    @PostMapping("/content/uploadInfo")
    public @ResponseBody R uploadInfo(@RequestBody InfoForm form) {
        try {
            StringBuffer sb = new StringBuffer(form.getText());
            String fileName = UUID.randomUUID().toString() + System.currentTimeMillis() + ".txt";
            FileOutputStream fos = new FileOutputStream(FrogConstant.Path.TEXT_URL + fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
            String url = "";
            // 腾讯云
            File file = new File(FrogConstant.Path.TEXT_URL + fileName);
            url = UploadUtils.uploadServerFile(file, "frogx/meet-text");
            return R.ok(url);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }
    /**
     * 上传COS
     * @param file
     * @return
     */
    @ApiOperation("COS上传")
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        // 文件路径
        String url = "";
        // 腾讯云
        url = UploadUtils.uploadWebFile(file, "/course");
        return R.ok().put("filename",url);
    }

    @PostMapping("create")
    @ApiOperation("添加课程")
    public R  addCourse(@RequestBody @Validated AddCourseManageForm form){
        try {
            CourseManageEntity manage = new CourseManageEntity();
            BeanUtils.copyProperties(form,manage);
            manage.setOnlineTime(new Date());
            manage.setCreateTime(new Date());
            manage.setIsBuy(0);
            if(manage.getPrice()<0 && manage.getTruePrice()<0){
                return R.error("价格不可以为负数或优惠价不可以做负数");
            }
            manageService.save(manage);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * 根据发布者账号判断用户是否存在 返回1存在或者0不存在
     *
     * @return
     */
    @GetMapping("getuserByAnnouncer")
    @ApiOperation("根据发布者账号判断用户是否存在 返回1存在或者0不存在")
    public R getuserByAnnouncer(@RequestParam String announcer) {
        try {
            User user = userService.getOne(new QueryWrapper<User>().eq("phone", announcer));
            if (user == null) {
                return R.ok().put("data",0);
            } else {
                return R.ok().put("data",1);
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 课程上下架
     *
     * @return
     */
    @RequestMapping(value = "updateCourseManageState", method = RequestMethod.POST)
    @ApiOperation("课程上下架")
    public R updateCourseManageState(@RequestParam Integer id) {
        try {
            CourseManageEntity manage = manageService.getById(id);
            if(manage.getIsonline().equals(FrogConstant.CourseStatus.UPPER)){
                manage.setIsonline(FrogConstant.CourseStatus.LOWER);
            }else {
                manage.setIsonline(FrogConstant.CourseStatus.UPPER);
            }
            manageService.updateById(manage);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 课程删除
     *
     * @return
     */
    @RequestMapping(value = "deleteCourseManage", method = RequestMethod.POST)
    @ApiOperation("课程删除")
    public @ResponseBody R deleteCourseManage(@RequestParam Integer id) {
        try {
            int courseManage = sectionService.
                    count(new QueryWrapper<CourseManageSectionEntity>().eq("programid",id));
              if (courseManage > 0) {
              return R.error("课程下有章节");
              }
            CourseManageEntity manageEntity = manageService.getById(id);
            manageEntity.setDeleted(1);
            manageService.updateById(manageEntity);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取所有课程
     *
     * @return
     */
    @RequestMapping(value = "getAllCourse", method = RequestMethod.GET)
    @ApiOperation("获取所有课程")
    public @ResponseBody R getAllCourse(@RequestParam Map map) {
        try {
            Page page = manageService.selectManagePage(new QueryExt(map));
            return R.ok().put("data",page);
        } catch (Exception e) {

            return R.error(e.getMessage());
        }
    }

    /**
     * 课程推荐/取消推荐
     *
     */
    @RequestMapping(value = "updateCourseManageIsRecommend", method = RequestMethod.POST)
    @ApiOperation("课程推荐/取消推荐")
    public R updateCourseManageIsrecommend(Integer id) {
        try {
            CourseManageEntity manageEntity = manageService.getById(id);
            if(manageEntity.getIsrecommend().equals(FrogConstant.CourseStatus.UPPER)){
                manageEntity.setIsrecommend(FrogConstant.CourseStatus.LOWER);
            }else {
                manageEntity.setIsrecommend(FrogConstant.CourseStatus.UPPER);
            }
            manageEntity.setUpdateTime(new Date());
            manageService.updateById(manageEntity);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * 课程编辑
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ApiOperation("课程编辑")
    public R updateCourseManage(@RequestBody  @Validated AddCourseManageForm form) {
        try {
            if(form.getId()==null){
                return R.error("课程id不能为空");
            }
            CourseManageEntity courseManageEntity = manageService.getById(form.getId());
            BeanUtils.copyProperties(form,courseManageEntity);
            courseManageEntity.setId(form.getId());
            System.out.println(form.getIcon());
            if (courseManageEntity.getIsonline() == 1) {
                return R.error("课程处于上架状态");
            }
            manageService.updateById(courseManageEntity);
            return R.ok("编辑成功");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }
}
